# Copyright [2011] [Ilya Rudakov]
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from cStringIO import StringIO
from job_manager.models import Feed
import os
from job_manager.utils.logging_utils import getlogger

__author__ = 'irudakov'

log = getlogger(__name__)

def get_feed_logs_file_names(feed):
    logs_path = "%s/logs" % feed.path
    return filter(lambda item: item.endswith(".log"), os.listdir(logs_path))

def read_log(feed_id, log_file_name, start_byte):
    feed = Feed.objects.get(id=feed_id)
    log_file_path = "%s/logs/%s" % (feed.path, log_file_name)

    log.debug("Opening log file with path:%s" % log_file_path)

    log_file = None
    string_buffer = None
    try:
        log_file = open(log_file_path, "r")
        log_file.seek(int(start_byte))
        string_buffer = StringIO()

        for line in log_file:
            string_buffer.write(line)
        return {"log_content":string_buffer.getvalue(), "finished_byte":log_file.tell()}
    finally:
        if log_file is not None:
            log_file.close()
        if string_buffer is not None:
            string_buffer.close()
